package com.wealth.system.service;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import com.wealth.system.entity.Permission;
import com.wealth.system.entity.Role;
import com.wealth.system.entity.User;

import iaas.enums.StatusEnum;

/**
 * 用户登录验证，和权限验证
 * @author chan
 *
 */
public class ShiroDbRealm extends AuthorizingRealm{

	Logger logger = Logger.getLogger(ShiroDbRealm.class);
	
	@Autowired
	private IUserService userService;
	
	/**
	 * doGetAuthorizationInfo ： 验证当前Subject（可理解为当前用户）所拥有的权限，且给其授权。
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		
		if (principals == null) {
            throw new AuthorizationException("PrincipalCollection method argument cannot be null.");
        }
        String username = ShiroUser.getInstance().getUser().getUsername();
        User user = userService.findUserByUsername(username);
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		
		List<String> roles = new ArrayList<String>();
		List<String> premissions = new ArrayList<String>();
		if(user != null){
			if(user.getRoleList()!=null && user.getRoleList().size()>0){
				for (Role role : user.getRoleList()) {
					if(role.getStatus()==StatusEnum.NORMAL.getValue()){
						roles.add(role.getName());
						if(role.getPermissions() != null && role.getPermissions().size()>0){
							for (Permission permission : role.getPermissionList()) {
								if(StringUtils.isNotBlank(permission.getPermission())){
									premissions.add(permission.getPermission());
								}
							}
						}
					}
				}
			}
		}else{
			logger.info("用户【"+username +"】不存在！");
			throw new AuthenticationException();
		}
		//设置角色
		info.addRoles(roles);
		//设置权限
		info.addStringPermissions(premissions);
		
		return info;
	}

	/**
     *  认证回调函数,登录时调用.
     *  doGetAuthenticationInfo ： 验证当前Subject登录。
     */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken arg0) throws AuthenticationException {
		logger.info("认证回调函数,登录时调用.");
		
		//根据用户名查询用户信息
		//User user = userService.getUserByUsername((UsernamePasswordToken) arg0);
		UsernamePasswordToken token = (UsernamePasswordToken) arg0;
		User user = userService.findUserByUsername(token.getUsername() );
		
		if(user==null){
			throw new UnknownAccountException();//没找到帐号
		}else{
			return new SimpleAuthenticationInfo(
				user,user.getPassword(),getName());
		}
	}

	
}
